import { fabric } from 'fabric'
import { useEffect, useRef, useState } from 'react'

export default function View() {
  let canvas: fabric.Canvas
  // let canvas2: fabric.Canvas
  const canvas2 = useRef<fabric.Canvas>()
  const [json, setJson] = useState<{
    version: string
    objects: fabric.Object[]
  }>()

  // 矩形
  const rect = new fabric.Rect({
    top: 30,
    left: 30,
    width: 30,
    height: 30,
    fill: 'darkcyan'
  })

  // 圆形
  const circle = new fabric.Circle({
    top: 30,
    left: 100,
    radius: 30,
    fill: '#aa96da'
  })

  const toJSON = () => {
    const result = canvas.toJSON()
    setJson(result)
    console.log('🚀 ~ toJSON ~ result:', result)
  }

  const loadFromJSON = () => {
    canvas2.current?.loadFromJSON(json, canvas2.current.renderAll.bind(canvas2.current))
  }

  useEffect(() => {
    canvas = new fabric.Canvas('c', {
      width: 1000,
      height: 1000
    })
    canvas2.current = new fabric.Canvas('c2', {
      width: 1000,
      height: 1000
    })

    canvas.add(rect, circle)

    // 监听画布点击鼠标事件
    canvas.on('mouse:down', options => {
      console.log(`当前选中的元素：${options.target ? options.target.type : 'canvas'}`)
      console.log(options) // 将点击事件获得的对象输出到控制台
    })

    // 监听画布点击鼠标事件
    canvas.on('mouse:up', options => {
      console.log('mouse:up事件：', options)
    })

    // 监听矩形移动
    rect.on('moving', options => {
      console.log('rect moving事件：', options)
    })
  }, [])

  return (
    <div className='view-wrapper'>
      <button onClick={() => toJSON()}>保存为JSON</button>
      <button onClick={() => loadFromJSON()}>导入数据</button>
      <canvas id='c' style={{ border: '1px solid #ccc' }}></canvas>
      <canvas id='c2' style={{ border: '1px solid #ccc' }}></canvas>
    </div>
  )
}
